package com.tenement.controller.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tenement.utils.imageVerify.RandomValidateCodeUtil;

/**
 * 图片验证码工具类
 * 
 * @author wk
 *
 */
@Controller
public class ImageUtilController {

	private static final Log logger = LogFactory.getLog(ImageUtilController.class);

	/**
	 * 生成图片验证码
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "getImgVerify.action")
	public void getImgVerify(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
			response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
			logger.error("获取验证码失败>>>>   ", e);
		}
	}

	/**
	 * 校验用户输入的图片验证码
	 * 
	 * @param requestMap
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/checkImgVerify.action")
	public @ResponseBody boolean checkVerify(@RequestBody String imageVal, HttpSession session) {
		try {
			// 从session中获取随机数
			String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
			logger.info("【-用户注册，用户输入的图片校验码-】" + "【-" + imageVal + "-】"+"【random】"+random);
			if (random == null) {
				return false;
			}
			if (random.equals(imageVal)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("验证码校验失败", e);
			return false;
		}
	}

}
